package com.cg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cg.dto.DeleteLikeDTO;
import com.cg.entity.UserLike;
import com.cg.mapper.LikeMapper;
import com.cg.result.R;
import com.cg.service.AccountService;
import com.cg.service.ILikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 加
 * @since 2025-01-17
 */
@Service
public class LikeServiceImpl extends ServiceImpl<LikeMapper, UserLike> implements ILikeService {
    @Autowired
    private ILikeService likeService;
    @Autowired
    private AccountService accountService;
    @Override
    public R<List<UserLike>> showLikes(Long userId) {
        LambdaQueryWrapper<UserLike> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(UserLike::getUserId,userId);
        List<UserLike> likeList=list(queryWrapper);
        if(likeList!=null) {
            return R.Success(likeList);
        }
        return R.Failed("未找到");
    }

    @Override
    public Long selectUserIdByLikeId(Long likeId) {
        UserLike like=getById(likeId);
        Long userId=like.getUserId();
        return userId;
    }

    @Override
    public UserLike selectLikeById(Long likeId) {
        UserLike like=getById(likeId);
        if (like!=null) {
            return like;
        }return null;
    }


    @Override
    public R deleteLike(DeleteLikeDTO deleteLikeDTO) {
        if(deleteLikeDTO.getLikeId()==null||likeService.selectLikeById(deleteLikeDTO.getLikeId())==null){
            return  R.Failed("不可删除，不存在该收藏");
        }
        Long userId1 = accountService.getCurrentUserId();
        if (!Objects.equals(likeService.selectUserIdByLikeId(deleteLikeDTO.getLikeId()), userId1)) {
            return R.Failed("不可删除当前收藏");
        } else {
            UserLike like = likeService.getById(deleteLikeDTO.getLikeId());
            likeService.removeById(like);
            return R.Success("取消收藏成功");
        }
    }
}
